{% extends "base.html" %}
{% block title %}区域分析 - {{ app_name }}{% endblock %}

{% block extra_css %}
<!-- 导入设计系统 -->
<link rel="stylesheet" href="/static/css/design-system/index.css">
<!-- 使用本地Leaflet CSS -->
<link rel="stylesheet" href="/static/vendor/leaflet/leaflet.css">
<style>
    /* 页面特定样式 */
    .map-container {
        height: 500px;
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: var(--shadow);
    }

    .stat-card-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: var(--spacing-4);
        margin-bottom: var(--spacing-6);
    }

    .main-content-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: var(--spacing-6);
        margin-bottom: var(--spacing-6);
    }

    .charts-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
        gap: var(--spacing-6);
        margin-bottom: var(--spacing-6);
    }

    .confidence-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: var(--spacing-6);
    }

    .region-list-item {
        padding: var(--spacing-3);
        border-bottom: 1px solid var(--color-border-primary);
        cursor: pointer;
        transition: background-color var(--transition-fast) var(--ease-in-out);
    }

    .region-list-item:hover {
        background-color: var(--color-bg-secondary);
    }

    .region-list-item:last-child {
        border-bottom: none;
    }

    .confidence-bar {
        height: 8px;
        background-color: var(--color-bg-secondary);
        border-radius: var(--radius-full);
        overflow: hidden;
        margin-top: var(--spacing-2);
    }

    .confidence-fill {
        height: 100%;
        background-color: var(--color-primary);
        transition: width var(--transition-normal) var(--ease-in-out);
    }

    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: var(--z-50);
    }

    .loading-overlay.active {
        display: flex;
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .map-container {
            height: 350px;
        }

        .main-content-grid {
            grid-template-columns: 1fr;
        }

        .charts-grid {
            grid-template-columns: 1fr;
        }

        .confidence-grid {
            grid-template-columns: 1fr;
        }
    }

    @media (min-width: 769px) and (max-width: 1024px) {
        .map-container {
            height: 400px;
        }

        .charts-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    /* 地图标记样式 */
    .cluster-marker {
        background-color: var(--color-primary);
        color: white;
        border-radius: 50%;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: var(--font-weight-semibold);
        font-size: var(--font-size-sm);
    }

    /* 通知样式 */
    .notification {
        position: fixed;
        top: var(--spacing-4);
        right: var(--spacing-4);
        z-index: var(--z-50);
        min-width: 300px;
        border-radius: var(--radius);
        box-shadow: var(--shadow-lg);
        transform: translateX(100%);
        transition: transform var(--transition-normal) var(--ease-in-out);
    }

    .notification.show {
        transform: translateX(0);
    }

    .notification-success {
        background-color: var(--color-success);
        color: white;
    }

    .notification-error {
        background-color: var(--color-error);
        color: white;
    }

    .notification-content {
        display: flex;
        align-items: center;
        padding: var(--spacing-3);
        gap: var(--spacing-2);
    }

    .notification-icon {
        flex-shrink: 0;
    }

    .notification-message {
        flex: 1;
        font-weight: var(--font-weight-medium);
    }
</style>
{% endblock %}

{% block content %}
<div class="page">
    <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
            <div class="header">
                <div class="header-brand">
                    <i class="fas fa-map-marked-alt header-icon text-primary"></i>
                    <h1 class="header-title">区域分析</h1>
                </div>
                <div class="header-actions">
                    <button class="btn btn-primary" onclick="refreshAnalysis()">
                        <i class="fas fa-sync-alt"></i>
                        刷新数据
                    </button>
                    <button class="btn btn-success" onclick="exportData()">
                        <i class="fas fa-download"></i>
                        导出数据
                    </button>
                </div>
            </div>
        </div>

        <div class="page-content">
            <!-- 筛选条件 -->
            <div class="content-section">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">筛选条件</h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <label class="form-label">分析任务</label>
                                <select class="input" id="taskFilter">
                                    <option value="">全部任务</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">区域级别</label>
                                <select class="input" id="regionLevelFilter">
                                    <option value="">全部级别</option>
                                    <option value="city">市级</option>
                                    <option value="district">区县级</option>
                                    <option value="street">街道级</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">开始时间</label>
                                <input type="date" class="input" id="startDate">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">结束时间</label>
                                <input type="date" class="input" id="endDate">
                            </div>
                        </div>
                        <div class="row mt-4">
                            <div class="col-md-6">
                                <label class="form-label">区域筛选</label>
                                <input type="text" class="input" id="regionFilter" placeholder="输入区域名称">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">最小置信度</label>
                                <input type="number" class="input" id="minConfidence" min="0" max="1" step="0.1" placeholder="0.0">
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <button class="btn btn-primary w-full" onclick="applyFilters()">
                                    <i class="fas fa-filter"></i>
                                    应用筛选
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 统计概览 -->
            <div class="content-section">
                <div class="stat-card-grid" id="statsContainer">
                    <!-- 统计卡片将通过JavaScript动态生成 -->
                </div>
            </div>

            <!-- 主要内容区域 -->
            <div class="content-section">
                <div class="main-content-grid">
                    <!-- 地图可视化 -->
                    <div>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">地理分布</h3>
                                <div class="btn-group">
                                    <button class="btn btn-sm btn-secondary active" onclick="switchMapView('points')">点位</button>
                                    <button class="btn btn-sm btn-secondary" onclick="switchMapView('heatmap')">热力图</button>
                                    <button class="btn btn-sm btn-secondary" onclick="switchMapView('cluster')">聚类</button>
                                </div>
                            </div>
                            <div class="card-body p-0">
                                <div id="map" class="map-container"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 区域列表 -->
                    <div>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">区域排行</h3>
                            </div>
                            <div class="card-body">
                                <div id="regionList" class="custom-scrollbar" style="max-height: 500px; overflow-y: auto;">
                                    <!-- 区域列表将在这里动态生成 -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 图表分析 -->
            <div class="content-section">
                <div class="charts-grid">
                    <!-- 区域分布图 -->
                    <div>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">区域分布</h3>
                            </div>
                            <div class="card-body">
                                <div id="regionChart" style="height: 400px;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 时间趋势图 -->
                    <div>
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">时间趋势</h3>
                            </div>
                            <div class="card-body">
                                <div id="timeChart" style="height: 400px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 置信度分析 -->
            <div class="content-section">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">置信度分析</h3>
                    </div>
                    <div class="card-body">
                        <div class="confidence-grid">
                            <div>
                                <div id="confidenceChart" style="height: 400px;"></div>
                            </div>
                            <div>
                                <h4 class="text-lg font-semibold mb-4">置信度分布详情</h4>
                                <div id="confidenceDetails">
                                    <!-- 置信度详情将在这里动态生成 -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载遮罩 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="text-center">
        <div class="spinner spinner-lg"></div>
        <p class="text-white mt-4">正在加载数据...</p>
    </div>
</div>

<!-- 通知容器 -->
<div id="notificationContainer"></div>
{% endblock %}

{% block extra_js %}
<!-- 导入基础组件库 -->
<script src="/static/js/components/base/BaseComponent.js"></script>
<script src="/static/js/components/base/StatCard.js"></script>
<script src="/static/js/components/base/FilterPanel.js"></script>
<script src="/static/js/components/base/ChartContainer.js"></script>

<!-- 导入工具类库 -->
<script src="/static/js/utils/index.js"></script>

<!-- 导入第三方库 -->
<script src="/static/vendor/leaflet/leaflet.js"></script>
<script src="/static/vendor/echarts/echarts.min.js"></script>
<script src="/static/vendor/leaflet/leaflet.heat.js"></script>

<!-- 页面应用逻辑 -->
<script>
// 全局变量
let map;
let currentMapView = 'points';
let regionChart;
let timeChart;
let confidenceChart;
let currentData = null;
let apiClient;
let cacheManager;
let errorHandler;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

// 初始化应用
function initializeApp() {
    // 初始化工具类
    apiClient = utils.getApiClient({
        baseUrl: '',
        timeout: 30000,
        debug: false
    });

    cacheManager = utils.getCacheManager({
        storage: 'localStorage',
        defaultTTL: 300000, // 5分钟
        debug: false
    });

    errorHandler = utils.getErrorHandler({
        debug: false,
        enableNotifications: true,
        enableLogging: true
    });

    // 设置认证令牌
    const token = getAuthToken();
    if (token) {
        apiClient.setAuthToken(token);
    }

    // 初始化地图和图表
    initializeMap();
    initializeCharts();

    // 加载数据
    loadInitialData();
}

// 初始化地图
function initializeMap() {
    try {
        map = L.map('map').setView([39.9042, 116.4074], 10); // 默认北京坐标

        // 定义瓦片源
        const tileSources = [
            {
                name: 'OpenStreetMap',
                url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                attribution: '© OpenStreetMap contributors'
            },
            {
                name: 'Stadia Maps',
                url: 'https://tiles.stadiamaps.com/tiles/osm/{z}/{x}/{y}.png',
                attribution: '© Stadia Maps, © OpenStreetMap contributors'
            },
            {
                name: 'ArcGIS',
                url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
                attribution: '© Esri, © OpenStreetMap contributors'
            }
        ];

        // 尝试加载瓦片源
        let tileLayerLoaded = false;
        for (let i = 0; i < tileSources.length; i++) {
            const source = tileSources[i];
            try {
                const tileLayer = L.tileLayer(source.url, {
                    attribution: source.attribution,
                    maxZoom: 19,
                    errorTileUrl: ''
                });

                tileLayer.addTo(map);
                tileLayerLoaded = true;
                console.log(`地图瓦片源加载成功: ${source.name}`);
                break;
            } catch (error) {
                console.warn(`瓦片源 ${source.name} 加载失败:`, error);
                continue;
            }
        }

        if (!tileLayerLoaded) {
            showMapError('所有地图瓦片源加载失败');
        }

        console.log('地图初始化完成');
    } catch (error) {
        console.error('地图初始化失败:', error);
        showMapError('地图初始化失败');
    }
}

// 显示地图错误
function showMapError(message) {
    const mapContainer = document.getElementById('map');
    if (mapContainer) {
        mapContainer.innerHTML = `
            <div class="flex items-center justify-center h-full bg-gray-100 rounded-lg">
                <div class="text-center">
                    <i class="fas fa-exclamation-triangle text-4xl text-yellow-500 mb-4"></i>
                    <p class="text-gray-600 mb-2">${message}</p>
                    <p class="text-sm text-gray-500">请检查网络连接或稍后重试</p>
                    <button onclick="initializeMap()" class="btn btn-primary mt-4">
                        重新加载
                    </button>
                </div>
            </div>
        `;
    }
}

// 初始化图表
function initializeCharts() {
    // 区域分布图
    regionChart = echarts.init(document.getElementById('regionChart'));

    // 时间趋势图
    timeChart = echarts.init(document.getElementById('timeChart'));

    // 置信度分析图
    confidenceChart = echarts.init(document.getElementById('confidenceChart'));

    // 设置默认选项
    regionChart.setOption({
        title: { text: '区域分布统计' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'value' },
        yAxis: { type: 'category', data: [] },
        series: [{ name: '数量', type: 'bar', data: [] }]
    });

    timeChart.setOption({
        title: { text: '时间趋势' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value' },
        series: [{ name: '数量', type: 'line', data: [], smooth: true }]
    });

    confidenceChart.setOption({
        title: { text: '置信度分布' },
        tooltip: { trigger: 'item' },
        series: [{ name: '置信度分布', type: 'pie', radius: '50%', data: [] }]
    });
}

// 加载初始数据
async function loadInitialData() {
    showLoading(true);
    try {
        await Promise.all([
            loadAnalysisTasks(),
            loadSummaryData(),
            loadRegionalAnalysis()
        ]);
    } catch (error) {
        console.error('加载初始数据失败:', error);
        showNotification('加载数据失败，请刷新页面重试', 'error');
    } finally {
        showLoading(false);
    }
}

// 加载分析任务
async function loadAnalysisTasks() {
    try {
        const cacheKey = 'analysis_tasks';
        const cachedTasks = await cacheManager.get(cacheKey);

        if (cachedTasks) {
            populateTaskSelect(cachedTasks);
            return;
        }

        const response = await apiClient.get('/api/analysis-tasks?status=completed&limit=100');
        if (response.status === 200) {
            const tasks = response.data.tasks || response.data.items || response.data || [];
            await cacheManager.set(cacheKey, tasks, 300000); // 缓存5分钟
            populateTaskSelect(tasks);
        }
    } catch (error) {
        console.error('加载分析任务失败:', error);
    }
}

// 填充任务选择框
function populateTaskSelect(tasks) {
    const taskSelect = document.getElementById('taskFilter');
    taskSelect.innerHTML = '<option value="">全部任务</option>';

    tasks.forEach(task => {
        const option = document.createElement('option');
        option.value = task.id;
        option.textContent = task.name || `任务 ${task.id}`;
        taskSelect.appendChild(option);
    });
}

// 加载摘要数据
async function loadSummaryData() {
    try {
        const params = buildFilterParams();
        const cacheKey = `regional_summary_${params}`;
        const cachedSummary = await cacheManager.get(cacheKey);

        if (cachedSummary) {
            updateStatsCards(cachedSummary);
            return;
        }

        const response = await apiClient.get(`/api/regional-analysis/summary?${params}`);
        if (response.status === 200) {
            const data = response.data;
            await cacheManager.set(cacheKey, data, 180000); // 缓存3分钟
            updateStatsCards(data);
        }
    } catch (error) {
        console.error('加载摘要数据失败:', error);
    }
}

// 更新统计卡片
function updateStatsCards(data) {
    const statsContainer = document.getElementById('statsContainer');

    const stats = [
        {
            title: '总记录数',
            value: data.basic_statistics?.total_count?.toLocaleString() || '0',
            icon: 'fas fa-database',
            color: 'primary'
        },
        {
            title: '覆盖区域',
            value: (data.total_regions || 0).toLocaleString(),
            icon: 'fas fa-map-marker-alt',
            color: 'success'
        },
        {
            title: '坐标覆盖率',
            value: `${data.coordinate_coverage || 0}%`,
            icon: 'fas fa-map-pin',
            color: 'info'
        },
        {
            title: '平均置信度',
            value: (data.basic_statistics?.average_confidence || 0).toFixed(2),
            icon: 'fas fa-chart-line',
            color: 'warning'
        }
    ];

    statsContainer.innerHTML = stats.map(stat => `
        <div class="card stat-card">
            <div class="card-body">
                <div class="flex items-center justify-between">
                    <div>
                        <div class="text-2xl font-bold text-gray-800">${stat.value}</div>
                        <div class="text-sm text-gray-500 mt-1">${stat.title}</div>
                    </div>
                    <div class="text-${stat.color}">
                        <i class="${stat.icon} text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 加载区域分析
async function loadRegionalAnalysis() {
    try {
        const filterRequest = buildFilterRequest();
        const cacheKey = `regional_analysis_${JSON.stringify(filterRequest)}`;
        const cachedAnalysis = await cacheManager.get(cacheKey);

        if (cachedAnalysis) {
            currentData = cachedAnalysis;
            updateVisualizations();
            return;
        }

        const response = await apiClient.post('/api/regional-analysis/analyze', filterRequest);
        if (response.status === 200) {
            currentData = response.data;
            await cacheManager.set(cacheKey, currentData, 300000); // 缓存5分钟
            updateVisualizations();
        }
    } catch (error) {
        console.error('加载区域分析失败:', error);
        showNotification('加载分析数据失败', 'error');
    }
}

// 更新可视化
function updateVisualizations() {
    if (!currentData) return;

    updateMap();
    updateCharts();
    updateRegionList();
    updateConfidenceAnalysis();
}

// 更新地图
function updateMap() {
    if (!currentData?.geographical_data) return;

    // 清除现有图层
    map.eachLayer(function(layer) {
        if (layer instanceof L.Marker || layer instanceof L.HeatLayer) {
            map.removeLayer(layer);
        }
    });

    const geoData = currentData.geographical_data;

    if (currentMapView === 'points') {
        addPointMarkers(geoData);
    } else if (currentMapView === 'heatmap') {
        addHeatmap(geoData);
    } else if (currentMapView === 'cluster') {
        addClusterMarkers(geoData);
    }
}

// 添加点位标记
function addPointMarkers(geoData) {
    const markers = geoData.map(point =>
        L.marker([point.lat, point.lng])
            .bindPopup(createPopupContent(point))
    );

    // 添加到地图
    markers.forEach(marker => map.addLayer(marker));

    // 调整视图
    if (markers.length > 0) {
        const group = L.featureGroup(markers);
        map.fitBounds(group.getBounds().pad(0.1));
    }
}

// 添加热力图
function addHeatmap(geoData) {
    if (typeof L.heatLayer === 'undefined') {
        console.warn('热力图插件未加载，降级显示点位');
        addPointMarkers(geoData);
        return;
    }

    const heatData = geoData.map(point => [
        point.lat,
        point.lng,
        point.confidence || 1.0
    ]);

    const heatLayer = L.heatLayer(heatData, {
        radius: 25,
        blur: 15,
        maxZoom: 17,
        gradient: {
            0.0: 'blue',
            0.2: 'cyan',
            0.4: 'lime',
            0.6: 'yellow',
            0.8: 'orange',
            1.0: 'red'
        }
    }).addTo(map);
}

// 添加聚类标记
function addClusterMarkers(geoData) {
    const regionGroups = {};

    geoData.forEach(point => {
        const region = point.region || '未知区域';
        if (!regionGroups[region]) {
            regionGroups[region] = {
                center: [point.lat, point.lng],
                count: 0,
                points: []
            };
        }
        regionGroups[region].count++;
        regionGroups[region].points.push(point);
    });

    Object.entries(regionGroups).forEach(([region, group]) => {
        const marker = L.marker(group.center, {
            icon: L.divIcon({
                className: 'cluster-marker',
                html: `<div class="cluster-marker">${group.count}</div>`,
                iconSize: [32, 32],
                iconAnchor: [16, 16]
            })
        }).bindPopup(`
            <div class="p-3">
                <h6 class="font-semibold mb-2">${region}</h6>
                <p class="text-sm mb-1"><strong>数量:</strong> ${group.count} 条记录</p>
                <p class="text-sm"><strong>平均置信度:</strong> ${(group.points.reduce((sum, p) => sum + p.confidence, 0) / group.points.length * 100).toFixed(1)}%</p>
            </div>
        `);
        map.addLayer(marker);
    });
}

// 创建弹窗内容
function createPopupContent(point) {
    return `
        <div class="p-3">
            <h6 class="font-semibold mb-2">${point.region}</h6>
            <div class="space-y-1 text-sm">
                <p><strong>地址:</strong> ${point.address || '未知'}</p>
                <p><strong>内容:</strong> ${point.complaint_content || '未知'}</p>
                <p><strong>置信度:</strong> ${(point.confidence * 100).toFixed(1)}%</p>
                <p><strong>时间:</strong> ${new Date(point.created_at).toLocaleString()}</p>
            </div>
        </div>
    `;
}

// 更新图表
function updateCharts() {
    if (!currentData) return;

    // 更新区域分布图
    if (currentData.regional_distribution) {
        const regionOption = {
            title: { text: '区域分布统计' },
            tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            xAxis: { type: 'value' },
            yAxis: {
                type: 'category',
                data: currentData.regional_distribution.regions.slice(0, 10)
            },
            series: [{
                name: '数量',
                type: 'bar',
                data: currentData.regional_distribution.counts.slice(0, 10),
                itemStyle: { color: '#3b82f6' }
            }]
        };
        regionChart.setOption(regionOption);
    }

    // 更新时间趋势图
    if (currentData.time_series) {
        const timeOption = {
            title: { text: '时间趋势' },
            tooltip: { trigger: 'axis' },
            xAxis: {
                type: 'category',
                data: currentData.time_series.map(item => item.date)
            },
            yAxis: { type: 'value' },
            series: [{
                name: '数量',
                type: 'line',
                data: currentData.time_series.map(item => item.count),
                smooth: true,
                itemStyle: { color: '#10b981' }
            }]
        };
        timeChart.setOption(timeOption);
    }
}

// 更新区域列表
function updateRegionList() {
    if (!currentData?.regional_distribution) return;

    const regionList = document.getElementById('regionList');
    const { regions, counts } = currentData.regional_distribution;

    regionList.innerHTML = regions.slice(0, 20).map((region, index) => `
        <div class="region-list-item" onclick="focusOnRegion('${region}')">
            <div class="flex justify-between items-center">
                <div>
                    <strong>${region}</strong>
                    <div class="text-gray-500 text-sm">${counts[index]} 条记录</div>
                </div>
                <div class="text-right">
                    <span class="badge badge-primary">${counts[index]}</span>
                </div>
            </div>
        </div>
    `).join('');
}

// 更新置信度分析
function updateConfidenceAnalysis() {
    if (!currentData?.confidence_distribution) return;

    const confidenceData = currentData.confidence_distribution;

    // 更新置信度图表
    const confidenceOption = {
        title: { text: '置信度分布' },
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        series: [{
            name: '置信度分布',
            type: 'pie',
            radius: '50%',
            data: confidenceData.ranges.map((range, index) => ({
                value: confidenceData.counts[index],
                name: range
            })),
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }]
    };
    confidenceChart.setOption(confidenceOption);

    // 更新置信度详情
    const details = document.getElementById('confidenceDetails');
    details.innerHTML = `
        <div class="mb-4">
            <div class="flex justify-between mb-2">
                <span>平均置信度</span>
                <strong>${(confidenceData.average_confidence * 100).toFixed(1)}%</strong>
            </div>
        </div>
        ${confidenceData.ranges.map((range, index) => `
            <div class="mb-3">
                <div class="flex justify-between mb-1">
                    <span>${range}</span>
                    <span>${confidenceData.counts[index]} (${confidenceData.distribution_percentage[range]}%)</span>
                </div>
                <div class="confidence-bar">
                    <div class="confidence-fill" style="width: ${confidenceData.distribution_percentage[range]}%"></div>
                </div>
            </div>
        `).join('')}
    `;
}

// 切换地图视图
function switchMapView(viewType) {
    currentMapView = viewType;

    // 更新按钮状态
    document.querySelectorAll('.btn-group .btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');

    updateMap();
}

// 聚焦到特定区域
function focusOnRegion(region) {
    if (!currentData?.geographical_data) return;

    const regionPoints = currentData.geographical_data.filter(point => point.region === region);

    if (regionPoints.length > 0) {
        const lats = regionPoints.map(p => p.lat);
        const lngs = regionPoints.map(p => p.lng);
        const bounds = L.latLngBounds([
            [Math.min(...lats), Math.min(...lngs)],
            [Math.max(...lats), Math.max(...lngs)]
        ]);

        map.fitBounds(bounds.pad(0.1));

        const avgConfidence = regionPoints.reduce((sum, p) => sum + p.confidence, 0) / regionPoints.length;

        L.popup()
            .setLatLng(bounds.getCenter())
            .setContent(`
                <div class="p-3">
                    <h6 class="font-semibold text-lg mb-2">${region}</h6>
                    <div class="space-y-2">
                        <div class="flex justify-between">
                            <span class="text-gray-600">记录数量:</span>
                            <span class="font-medium">${regionPoints.length} 条</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">平均置信度:</span>
                            <span class="font-medium">${(avgConfidence * 100).toFixed(1)}%</span>
                        </div>
                    </div>
                </div>
            `)
            .openOn(map);
    }
}

// 刷新分析
async function refreshAnalysis() {
    showLoading(true);
    try {
        // 清除相关缓存
        await cacheManager.clear('regional_');

        await Promise.all([
            loadSummaryData(),
            loadRegionalAnalysis()
        ]);

        showNotification('数据已刷新', 'success');
    } catch (error) {
        console.error('刷新数据失败:', error);
        showNotification('刷新数据失败', 'error');
    } finally {
        showLoading(false);
    }
}

// 导出数据
async function exportData() {
    try {
        const params = buildFilterParams();
        const response = await apiClient.get(`/api/regional-analysis/export?${params}&format=json`);

        if (response.status === 200) {
            const blob = new Blob([JSON.stringify(response.data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `区域分析数据_${new Date().toISOString().split('T')[0]}.json`;
            link.click();
            URL.revokeObjectURL(url);

            showNotification('数据导出成功', 'success');
        }
    } catch (error) {
        console.error('数据导出失败:', error);
        showNotification('数据导出失败', 'error');
    }
}

// 应用筛选条件
async function applyFilters() {
    showLoading(true);
    try {
        await Promise.all([
            loadSummaryData(),
            loadRegionalAnalysis()
        ]);

        showNotification('筛选条件已应用', 'success');
    } catch (error) {
        console.error('应用筛选条件失败:', error);
        showNotification('应用筛选条件失败', 'error');
    } finally {
        showLoading(false);
    }
}

// 构建筛选参数
function buildFilterParams() {
    const params = new URLSearchParams();

    const taskId = document.getElementById('taskFilter').value;
    if (taskId) params.append('task_id', taskId);

    const startDate = document.getElementById('startDate').value;
    if (startDate) params.append('start_date', startDate);

    const endDate = document.getElementById('endDate').value;
    if (endDate) params.append('end_date', endDate);

    const region = document.getElementById('regionFilter').value;
    if (region) params.append('region', region);

    const regionLevel = document.getElementById('regionLevelFilter').value;
    if (regionLevel) params.append('region_level', regionLevel);

    const minConfidence = document.getElementById('minConfidence').value;
    if (minConfidence) params.append('min_confidence', minConfidence);

    return params.toString();
}

// 构建筛选请求
function buildFilterRequest() {
    return {
        task_id: document.getElementById('taskFilter').value || null,
        start_date: document.getElementById('startDate').value || null,
        end_date: document.getElementById('endDate').value || null,
        region: document.getElementById('regionFilter').value || null,
        region_level: document.getElementById('regionLevelFilter').value || null,
        min_confidence: document.getElementById('minConfidence').value || null,
        limit: 1000,
        offset: 0
    };
}

// 获取认证令牌
function getAuthToken() {
    return localStorage.getItem('auth_token') || getCookie('auth_token');
}

// 获取Cookie
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

// 显示/隐藏加载遮罩
function showLoading(show) {
    const overlay = document.getElementById('loadingOverlay');
    if (show) {
        overlay.classList.add('active');
    } else {
        overlay.classList.remove('active');
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    const container = document.getElementById('notificationContainer');
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;

    const icon = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';

    notification.innerHTML = `
        <div class="notification-content">
            <div class="notification-icon">
                <i class="${icon}"></i>
            </div>
            <div class="notification-message">${message}</div>
        </div>
    `;

    container.appendChild(notification);

    // 触发显示动画
    setTimeout(() => notification.classList.add('show'), 100);

    // 自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 响应式处理
window.addEventListener('resize', function() {
    if (regionChart) regionChart.resize();
    if (timeChart) timeChart.resize();
    if (confidenceChart) confidenceChart.resize();
});
</script>
{% endblock %}